package buco.integrity.trigger;

import java.util.ArrayList;
import java.util.List;

import buco.core.api.*;

public class TriggerIntegrityCheck extends IntegrityCheck {
	
	@Override
	public void bundleAdded(Bundle bundle, IntegrityReport report) {
		for(RegisterTrigger trigger : getTrigger("bundleAdded", bundle)) {
			report.info(trigger.getMessage()); 
		}
	}
	
	/** 
	 * Called when a bundle is removed from the composition. 
	 */	
	@Override
	public void bundleRemoved(Bundle bundle, IntegrityReport report) {
		for(RegisterTrigger trigger : getTrigger("bundleRemoved", bundle)) {
			report.info(trigger.getMessage()); 
		}
	}
	
	/** 
	 * Called when a wire is activated or disabled. 
	 */
	@Override
	public void toggleWire(BundleWire wire, IntegrityReport report) {
		if(!wire.isWireActive()) 
			return; 
		
		Bundle to = wire.getTo(); 		
		((BundleIntegrityReport)report).setBundle(to); 
		for(RegisterTrigger trigger : getTrigger("packageImported", to)) {
			String packageName = trigger.getPackageName(); 
			
			for(Requirement req : wire.getRequirements()) {
				if(req instanceof ImportPackageRequirement) {
					if(((ImportPackageRequirement)req).getPackageName().equals(packageName)) {
						report.info(trigger.getMessage());
					}
				}
			}			
		}
	}
	
	private List<RegisterTrigger> getTrigger(String event, Bundle bundle) {
		List<RegisterTrigger> list = bundle.getSemanticConstraints("registerTrigger", RegisterTrigger.class);
		ArrayList<RegisterTrigger> ret = new ArrayList<RegisterTrigger>();
		
		for(RegisterTrigger trigger : list) {
			if(trigger.getEvent().equals(event)) {
				ret.add(trigger); 				
			}
		}
		
		return ret; 
	}
}
